﻿using System.Windows.Input;
using Omnia.Library;
using Omnia.DataModels;
using System.Linq;
using System.Windows;
using Omnia.Library.Extensions;

namespace Omnia.ViewModels
{
    public class CategoryEditViewModel : CategoryViewModel
    {
        public CategoryEditViewModel()
        {
            
        }

        private string guid;
        public string Guid
        {
            get { return guid; }
            set
            {
                guid = value;
                RaisePropertyChanged(() => Guid);
                if (Guid != null)
                {
                    CurrentEditItem = Database.CollectionOfCategories.FirstOrDefault(c => c.Guid == Guid);
                }
                RaisePropertyChanged(() => CurrentEditItem);
            }
        }

        private CategoryInfo currentEditItem = new CategoryInfo();
        public CategoryInfo CurrentEditItem
        {
            get { return currentEditItem; }
            set
            {
                currentEditItem = value;
                RaisePropertyChanged(() => CurrentEditItem);
            }
        }

        #region Method
        private void Update(CategoryInfo entity)
        {
            CategoryInfo targetItem = Database.CollectionOfCategories.FirstOrDefault(c => c.Guid == entity.Guid);
            if (entity.Default)
            {
                CategoryInfo defaultItem = Database.CollectionOfCategories.FirstOrDefault(c => c.Default && c.Kind == entity.Kind);
                if (defaultItem != null)
                {
                    defaultItem.Default = false;
                    Save();
                }
            }

            targetItem = entity;
            Save();
        }
        #endregion

        #region Commands
        public ICommand UpdateCommand
        {
            get
            {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate
                    {
                        Update(CurrentEditItem);
                        //MessageBox.Show(Application.Current.FindResource<string>(ResourceKeys.IDS_NOTE_CATE_UPDATE_OK), Application.Current.FindResource<string>(ResourceKeys.IDS_NOTE_CATE_UPDATE_TITLE), MessageBoxButton.OK);
                        NavigateBack();
                    }
                };
            }
        }
        #endregion
    }
}
